//
//  BDShopManagerViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/17.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDShopReservationViewController.h"
#import "BDShopManagerTableViewCell.h"
#import "BDShopCouponsTableViewCell.h"
#import "BDShopCouponsModel.h"
#import "BDUserModel.h"
#import "BDShopCouponsInfoViewController.h"
#import "CallExternalProcessBehavior.h"
#import "DatePickbehavior.h"
#import "BDPayViewController.h"

@interface BDShopReservationViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, strong) NSString *peopleNumber;
@property (nonatomic, strong) NSString *yuyueTime;
@property (nonatomic, strong) NSString *yuyuePhone;

@end

@implementation BDShopReservationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"预定");
    BDUserModel *user = [BDUserModel getCurrentUser];
    self.yuyuePhone = user.mobile;
    [self refreshDatasource];
    [self requestCoupond];
    
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray arrayWithObjects:[NSMutableArray array], [NSMutableArray array], nil];
    }
    return _datasource;
}

- (void)refreshDatasource{
    NSMutableArray *firstArray = @[@{@"title":ASLocalizedString(@"预约人数"), @"subTitle":[self.peopleNumber isNotEmpty] ? self.peopleNumber : @"", @"placeHold":ASLocalizedString(@"请输入预约人数")},
                                   @{@"title":ASLocalizedString(@"预约时间"), @"subTitle":[self.yuyueTime isNotEmpty] ? self.yuyueTime : @"", @"placeHold":ASLocalizedString(@"点击选择预约时间"), @"canEdit":@"NO"},
                                   @{@"title":ASLocalizedString(@"预约电话"), @"subTitle":[self.yuyuePhone isNotEmpty] ? self.yuyuePhone : @"", @"placeHold":ASLocalizedString(@"请输入预约电话")}].mutableCopy;
    [self.datasource setObject:firstArray atIndexedSubscript:0];
}

- (void)requestCoupond{
    [MBManager showLoadingAlert:ASLocalizedString(@"加载中")clickHidden:NO clickBlock:nil];
    NSString *url = [NSString stringWithFormat:@"%@shops/%@/coupons?id=%@&page=%@&size=%@&is_manager=0", KBDBaseURL, @(self.manager.shop_id), @(self.manager.shop_id), self.startPage, self.pageSize];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        [MBManager hideAlert];
        [self.datasource.lastObject addObjectsFromArray:[BDShopCouponsModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
        self.startPage = x[@"next_page"];
        self.isEnd = [x[@"is_end"] boolValue];
        
        [self.tableView reloadData];
//        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [MBManager hideAlert];
        [self showErrorViewWithTapBlock:^{
            [self requestCoupond];
        }];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 90;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 35;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    
    UIView *bkView = [[UIView alloc] initWithFrame:view.bounds];
    bkView.backgroundColor = [UIColor whiteColor];
    [view addSubview:bkView];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = ASLocalizedString(@"购买超值套餐");
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = KBDColorBlue;
    [titleLabel sizeToFit];
    titleLabel.left = 10;
    titleLabel.centerY = view.height / 2.0;
    [view addSubview:titleLabel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 1)];
    line.backgroundColor = kBDColorGray;
    line.bottom = view.height;
    [view addSubview:line];
}

-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.size = CGSizeMake(kBDScreenWidth - 20, 40);
    button.centerX = kBDScreenWidth / 2.0;
    button.top = 10;
    button.backgroundColor = [UIColor colorWithHexString:@"#4d7aad"];
    [button setTitle:ASLocalizedString(@"预定")forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 4;
    [view addSubview:button];
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSString *alert = nil;
        if (![self.peopleNumber isNotEmpty]) {
            alert = ASLocalizedString(@"请填写预约人数");
        }else if (![self.yuyueTime isNotEmpty]){
            alert = ASLocalizedString(@"请选择预约时间");
        }else if (![self.yuyuePhone isNotEmpty]) {
            alert = ASLocalizedString(@"请填写正确的手机号码");
        }
        if ([alert isNotEmpty]) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
            return;
        }
        
        [MBManager showLoadingAlert:ASLocalizedString(@"正在预约")clickHidden:NO clickBlock:nil];
        
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];//设定时间格式
        NSTimeInterval timeInterval = [[dateFormat dateFromString:self.yuyueTime] timeIntervalSince1970];
        
        NSString *url = [NSString stringWithFormat:@"%@booked", KBDBaseURL];
        NSString *headValid = [BDUserModel getHeaderValidation];
        NSDictionary *para = @{@"shop_id":@(self.manager.shop_id),
                               @"manager_user_id":@(self.manager.user_id),
                               @"time":@(timeInterval),
                               @"num":self.peopleNumber,
                               @"mobile":self.yuyuePhone};
        
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:ASLocalizedString(@"预订成功")clickHidden:YES clickBlock:nil];
            
            //这里插入消息
//            NSString *from = [[EMClient sharedClient] currentUsername];
//            long long timeInterval = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970] * 1000;
//            EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:@"8" type:EMConversationTypeChat createIfNotExist:YES];
//            NSString *text = ASLocalizedString(@"你的预定已经提交成功，请注意查看回复结果。");
//            EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
//            EMMessage *locationMessage = [[EMMessage alloc] initWithConversationID:conversation.conversationId from:conversation.conversationId to:from body:body ext:nil];
//            locationMessage.chatType = EMConversationTypeChat;
//            locationMessage.timestamp = timeInterval;
//            EMError *error = nil;
//            [conversation insertMessage:locationMessage error:&error];
//
//            if (error == nil) {
//                [[ChatDemoHelper shareHelper] alertMessageReceivedWithMessage:locationMessage];
//            }
            
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:ASLocalizedString(@"预订失败")clickHidden:YES clickBlock:nil];
        }];
    }];
    
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = ASLocalizedString(@"预约成功之后1分钟内将收到预定短信，请注意查收");
    titleLabel.font = [UIFont systemFontOfSize:13];
    titleLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
    [titleLabel sizeToFit];
    titleLabel.left = 11;
    titleLabel.top = button.bottom + 10;
    [view addSubview:titleLabel];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 40;
    }
    return 125;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([self.datasource.lastObject count] != 0) {
        return self.datasource.count;
    }
    return self.datasource.count - 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.datasource[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        BDShopManagerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"managerCell" forIndexPath:indexPath];
        [cell configeWithModel:self.datasource[indexPath.section][indexPath.row] stringChangeBlock:^(NSString *changeString) {
            if (indexPath.row == 0) {
                self.peopleNumber = changeString;
            }else if (indexPath.row == 2) {
                self.yuyuePhone = changeString;
            }
            [self refreshDatasource];
        }];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        BDShopCouponsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"couponsCell" forIndexPath:indexPath];
        BDShopCouponsModel *coupondModel = self.datasource[indexPath.section][indexPath.row];
        [cell configeWithModel:coupondModel editButtonBlock:nil deletedButtonBlock:nil qianggouButtonBlock:^{
            [BDUserModel judgeCurrentUserWithNormalBlock:^{
                BDPayViewController *payVC = [[BDPayViewController alloc] init];
                payVC.product = coupondModel;
                payVC.shopTitle = self.shopTitle;
                payVC.payType = BDProductPayTypeCoupon;
                payVC.productId = [NSString stringWithFormat:@"%@", @(coupondModel.my_id)];
                payVC.price = [NSDecimalNumber decimalNumberWithString:coupondModel.discount_price];
                [self.navigationController pushViewController:payVC animated:YES];
            }];
        }];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            [DatePickbehavior getDateTimeByCurrentDate:nil startDate:nil endDate:nil finishBlock:^(NSString *finialDate) {
                self.yuyueTime = finialDate;
                [self refreshDatasource];
                [self.tableView reloadData];
            }];
        }
    }
    if (indexPath.section == 1) {
        BDShopCouponsInfoViewController *couponsInfoVC = [[BDShopCouponsInfoViewController alloc] init];
        BDShopCouponsModel *coupond = self.datasource[1][indexPath.row];
        couponsInfoVC.coupondModel = coupond;
        couponsInfoVC.manager = self.manager;
        couponsInfoVC.shopTitle = self.shopTitle;
        [self.navigationController pushViewController:couponsInfoVC animated:YES];
    }
}

- (UIView *)customHeaderView{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 85)];
    header.backgroundColor = [UIColor clearColor];
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 75)];
    contentView.backgroundColor = [UIColor whiteColor];
    [header addSubview:contentView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 55, 55)];
    imageView.left = 10;
    imageView.centerY = contentView.height / 2.0;
    
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.manager.cover] placeholderImage:[UIImage imageNamed:@"avatar"]];
    [contentView addSubview:imageView];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    nameLabel.text = self.manager.name;
    nameLabel.textColor = [UIColor colorWithHexString:@"#111111"];
    nameLabel.font = [UIFont systemFontOfSize:15];
    nameLabel.left = imageView.right + 10;
    nameLabel.centerY = contentView.height / 2.0;
    [contentView addSubview:nameLabel];
    
    UIButton *callButton = [UIButton buttonWithType:UIButtonTypeCustom];
    callButton.backgroundColor = [UIColor colorWithHexString:@"4d7aad"];
    callButton.layer.cornerRadius = 5;
    callButton.size = CGSizeMake(65, 30);
    callButton.right = kBDScreenWidth - 15;
    callButton.centerY = contentView.height / 2.0;
    [callButton setTitle:ASLocalizedString(@"联系")forState:UIControlStateNormal];
    callButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [callButton setImage:[UIImage imageNamed:@"lianxi"] forState:UIControlStateNormal];
    [callButton setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
    [contentView addSubview:callButton];
    [[callButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [CallExternalProcessBehavior phoneWithPhoneNumber:self.manager.mobile callFinished:^{
            NSDictionary *dict = @{MerchantType_callShop:self.shopTitle};
            [MobClick event:MerchantName_callShop attributes:dict];
        }];
    }];
    [callButton setEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
    return header;
}


- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = [self customHeaderView];
        [_tableView registerClass:[BDShopManagerTableViewCell class] forCellReuseIdentifier:@"managerCell"];
        [_tableView registerClass:[BDShopCouponsTableViewCell class] forCellReuseIdentifier:@"couponsCell"];
        
        _tableView.sectionFooterHeight = 10;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorInset = UIEdgeInsetsZero;
        [self.view addSubview:self.tableView];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
